package com.zhw.service.impl;


import com.zhw.Util.JwtUtils;
import com.zhw.anno.Login;
import com.zhw.mapper.UserMapper;
import com.zhw.pojo.dto.UpdatePasswordDTO;
import com.zhw.pojo.entry.User;
import com.zhw.service.UserService;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    HttpServletRequest request;
    @Override
    @Login
    public User login(User user) {
        return userMapper.check(user);
    }



    @Override
    public void updatePass(UpdatePasswordDTO updatePasswordDTO) {




        User user=new User();

        user.setUpdateDate(LocalDateTime.now());
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);
        String  username = (String) claims.get("username");
        String  password = (String) claims.get("password");
        user.setUsername(username);


        if(updatePasswordDTO.getOldPass().equals(password)){

            user.setPassword(updatePasswordDTO.getPassword());
            userMapper.update(user);
        }else {
            throw new RuntimeException("用户名密码不正确");
        }






    }

    @Override
    public User getUserInfo() {
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);
        String  username = (String) claims.get("username");
        String  password = (String) claims.get("password");
        User u=new User();
        u.setUsername(username);
        u.setPassword(password);


        return userMapper.check(u);
    }

    @Override
    public List<Map<String, String>> getUserName() {
        List<String> username = userMapper.getUsername();
        List<Map<String, String>> result=new ArrayList<>();

        for (String s : username) {
            Map m=new HashMap();
            m.put("label",s);
            m.put("value",s);
            result.add(m);

        }
        return result;
    }
}
